package com.example.a_java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.exception.BusinessException;
import com.example.a_java.mapper.StatisticsMapper;
import com.example.a_java.model.dto.report.*;
import com.example.a_java.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 统计报表服务实现�?
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private StatisticsMapper statisticsMapper;

    /**
     * 获取业务统计概览数据
     */
    @Override
    public BusinessStatsDTO getBusinessStats(LocalDate startDate, LocalDate endDate) {
        try {
            // 如果未指定日期，则默认为当月
            if (startDate == null) {
                startDate = LocalDate.now().withDayOfMonth(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 计算上个月的日期范围，用于环比计�?
            LocalDate lastPeriodStart = startDate.minusMonths(1);
            LocalDate lastPeriodEnd = endDate.minusMonths(1);
            
            // 查询业务统计数据
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("lastPeriodStart", lastPeriodStart);
            params.put("lastPeriodEnd", lastPeriodEnd);
            
            // 使用mapper查询数据库（假设这里存在方法�?
            Map<String, Object> statsData = statisticsMapper.getBusinessStatsOverview(params);
            
            // 构造返回对�?
            BusinessStatsDTO stats = new BusinessStatsDTO();
            stats.setApplyAmount(getBigDecimal(statsData, "applyAmount"));
            stats.setApplyRate(getBigDecimal(statsData, "applyRate"));
            stats.setDisburseAmount(getBigDecimal(statsData, "disburseAmount"));
            stats.setDisburseRate(getBigDecimal(statsData, "disburseRate"));
            stats.setCollectAmount(getBigDecimal(statsData, "collectAmount"));
            stats.setCollectRate(getBigDecimal(statsData, "collectRate"));
            stats.setCollectRateChange(getBigDecimal(statsData, "collectRateChange"));
            
            return stats;
        } catch (Exception e) {
            log.error("获取业务统计概览数据失败", e);
            throw new BusinessException("获取业务统计概览数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取业务图表数据
     */
    @Override
    public BusinessChartDTO getBusinessCharts(BusinessQueryDTO query) {
        try {
            // 处理默认�?
            if (query.getStartDate() == null) {
                // 默认�?个月
                query.setStartDate(LocalDate.now().minusMonths(5).withDayOfMonth(1));
            }
            if (query.getEndDate() == null) {
                query.setEndDate(LocalDate.now());
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", query.getStartDate());
            params.put("endDate", query.getEndDate());
            params.put("businessType", query.getBusinessType());
            
            // 查询图表数据
            List<Map<String, Object>> chartDataList = statisticsMapper.getBusinessChartData(params);
            
            // 构造返回对�?
            BusinessChartDTO chart = new BusinessChartDTO();
            
            // 处理图表数据
            processBusinessChartData(chart, chartDataList, query.getPeriod());
            
            return chart;
        } catch (Exception e) {
            log.error("获取业务图表数据失败", e);
            throw new BusinessException("获取业务图表数据失败: " + e.getMessage());
        }
    }

    /**
     * 处理业务图表数据
     */
    private void processBusinessChartData(BusinessChartDTO chart, List<Map<String, Object>> dataList, String period) {
        // 初始化数据结�?
        List<String> dates = new ArrayList<>();
        Map<String, List<BigDecimal>> amountTrend = new HashMap<>();
        Map<String, List<Integer>> countTrend = new HashMap<>();
        
        // 业务类型列表
        List<String> businessTypes = Arrays.asList("apply", "disburse", "collect");
        
        // 初始化各类型数据列表
        for (String type : businessTypes) {
            amountTrend.put(type, new ArrayList<>());
            countTrend.put(type, new ArrayList<>());
        }
        
        // 处理日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if ("month".equals(period)) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        } else if ("quarter".equals(period)) {
            formatter = DateTimeFormatter.ofPattern("yyyy-QQ");
        } else if ("year".equals(period)) {
            formatter = DateTimeFormatter.ofPattern("yyyy");
        }
        
        // 按日期分组汇总数�?
        Map<String, Map<String, Object>> dateGroupData = new HashMap<>();
        
        for (Map<String, Object> data : dataList) {
            String statsDate = data.get("stats_date").toString();
            String businessType = (String) data.get("business_type");
            
            if (!dateGroupData.containsKey(statsDate)) {
                dateGroupData.put(statsDate, new HashMap<>());
                dates.add(statsDate);
            }
            
            // 将当前记录添加到对应日期分组
            dateGroupData.get(statsDate).put(businessType + "_amount", data.get("amount"));
            dateGroupData.get(statsDate).put(businessType + "_count", data.get("count"));
            dateGroupData.get(statsDate).put(businessType + "_success_count", data.get("success_count"));
            dateGroupData.get(statsDate).put(businessType + "_success_rate", data.get("success_rate"));
        }
        
        // 对日期排�?
        Collections.sort(dates);
        
        // 填充图表数据
        for (String date : dates) {
            Map<String, Object> dateData = dateGroupData.get(date);
            
            for (String type : businessTypes) {
                // 金额趋势
                BigDecimal amount = getBigDecimal(dateData, type + "_amount");
                amountTrend.get(type).add(amount);
                
                // 笔数趋势
                Integer count = getInteger(dateData, type + "_count");
                countTrend.get(type).add(count);
            }
        }
        
        // 设置图表数据
        chart.setMonths(dates);
        chart.setAmountTrend(amountTrend);
        chart.setCountTrend(countTrend);
        
        // 计算类型分布
        List<Map<String, Object>> typeDistribution = calculateTypeDistribution(dataList);
        chart.setTypeDistribution(typeDistribution);
        
        // 计算状态分�?
        List<Map<String, Object>> statusDistribution = calculateStatusDistribution(dataList);
        chart.setStatusDistribution(statusDistribution);
    }

    /**
     * 计算业务类型分布
     */
    private List<Map<String, Object>> calculateTypeDistribution(List<Map<String, Object>> dataList) {
        // 按业务类型汇总金额和数量
        Map<String, BigDecimal> typeAmountMap = new HashMap<>();
        Map<String, Integer> typeCountMap = new HashMap<>();
        
        for (Map<String, Object> data : dataList) {
            String businessType = (String) data.get("business_type");
            BigDecimal amount = getBigDecimal(data, "amount");
            Integer count = getInteger(data, "count");
            
            typeAmountMap.put(businessType, typeAmountMap.getOrDefault(businessType, BigDecimal.ZERO).add(amount));
            typeCountMap.put(businessType, typeCountMap.getOrDefault(businessType, 0) + count);
        }
        
        // 构造分布数�?
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        for (Map.Entry<String, BigDecimal> entry : typeAmountMap.entrySet()) {
            String type = entry.getKey();
            Map<String, Object> item = new HashMap<>();
            item.put("type", type);
            item.put("value", entry.getValue());
            item.put("count", typeCountMap.get(type));
            
            // 翻译业务类型名称
            if ("apply".equals(type)) {
                item.put("name", "申请");
            } else if ("disburse".equals(type)) {
                item.put("name", "放款");
            } else if ("collect".equals(type)) {
                item.put("name", "回收");
            } else {
                item.put("name", type);
            }
            
            distribution.add(item);
        }
        
        return distribution;
    }

    /**
     * 计算业务状态分�?
     */
    private List<Map<String, Object>> calculateStatusDistribution(List<Map<String, Object>> dataList) {
        // 计算成功率和失败�?
        BigDecimal totalCount = BigDecimal.ZERO;
        BigDecimal successCount = BigDecimal.ZERO;
        
        for (Map<String, Object> data : dataList) {
            Integer count = getInteger(data, "count");
            Integer success = getInteger(data, "success_count");
            
            totalCount = totalCount.add(new BigDecimal(count));
            successCount = successCount.add(new BigDecimal(success));
        }
        
        List<Map<String, Object>> distribution = new ArrayList<>();
        
        if (totalCount.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal successRate = successCount.divide(totalCount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
            BigDecimal failureRate = new BigDecimal(100).subtract(successRate);
            
            Map<String, Object> successItem = new HashMap<>();
            successItem.put("name", "成功");
            successItem.put("value", successRate);
            successItem.put("count", successCount);
            distribution.add(successItem);
            
            Map<String, Object> failureItem = new HashMap<>();
            failureItem.put("name", "失败");
            failureItem.put("value", failureRate);
            failureItem.put("count", totalCount.subtract(successCount));
            distribution.add(failureItem);
        }
        
        return distribution;
    }

    /**
     * 获取业务明细列表
     */
    @Override
    public Page<BusinessDetailDTO> getBusinessList(BusinessQueryDTO query) {
        try {
            // 处理默认�?
            if (query.getCurrentPage() == null || query.getCurrentPage() < 1) {
                query.setCurrentPage(1);
            }
            if (query.getPageSize() == null || query.getPageSize() < 1) {
                query.setPageSize(10);
            }
            
            // 构造分页对�?
            Page<BusinessDetailDTO> page = new Page<>(query.getCurrentPage(), query.getPageSize());
            
            // 将查询参数转换为Map
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", query.getStartDate());
            params.put("endDate", query.getEndDate());
            params.put("businessType", query.getBusinessType());
            
            // 查询总数
            Integer total = statisticsMapper.countBusinessList(params);
            page.setTotal(total);
            
            // 查询明细列表
            List<BusinessDetailDTO> list = statisticsMapper.getBusinessList(params, (query.getCurrentPage() - 1) * query.getPageSize(), query.getPageSize());
            page.setRecords(list);
            
            return page;
        } catch (Exception e) {
            log.error("获取业务明细列表失败", e);
            throw new BusinessException("获取业务明细列表失败: " + e.getMessage());
        }
    }

    /**
     * 导出业务报表数据
     */
    @Override
    public byte[] exportBusinessReport(BusinessQueryDTO query) {
        try {
            // 创建Excel工作�?
            Workbook workbook = new XSSFWorkbook();
            
            // 导出类型：summary(汇�?、detail(明细)
            if ("summary".equals(query.getExportType())) {
                // 导出汇总数�?
                BusinessStatsDTO stats = getBusinessStats(query.getStartDate(), query.getEndDate());
                createBusinessSummarySheet(workbook, stats, query);
            } else {
                // 导出明细数据
                Page<BusinessDetailDTO> page = new Page<>(1, 10000); // 导出最�?0000�?
                
                // 将查询参数转换为Map
                Map<String, Object> params = new HashMap<>();
                params.put("startDate", query.getStartDate());
                params.put("endDate", query.getEndDate());
                params.put("businessType", query.getBusinessType());
                
                // 查询明细数据
                List<BusinessDetailDTO> list = statisticsMapper.getBusinessList(params, 0, 10000);
                createBusinessDetailSheet(workbook, list, query);
            }
            
            // 生成Excel文件字节�?
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("导出业务报表数据失败", e);
            throw new BusinessException("导出业务报表数据失败: " + e.getMessage());
        }
    }

    /**
     * 创建业务汇总数据工作表
     */
    private void createBusinessSummarySheet(Workbook workbook, BusinessStatsDTO stats, BusinessQueryDTO query) {
        // 此方法实现省略，用于创建Excel工作表并填充业务汇总数�?
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 创建业务明细数据工作�?
     */
    private void createBusinessDetailSheet(Workbook workbook, List<BusinessDetailDTO> list, BusinessQueryDTO query) {
        // 此方法实现省略，用于创建Excel工作表并填充业务明细数据
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 获取贷款统计概览数据
     */
    @Override
    public LoanStatsDTO getLoanStats(LoanQueryDTO query) {
        try {
            // 处理查询参数
            LocalDate startDate;
            LocalDate endDate;
            
            // 处理统计周期
            switch (query.getPeriod()) {
                case "month":
                    // 默认取当�?
                    YearMonth currentMonth = YearMonth.now();
                    startDate = currentMonth.atDay(1);
                    endDate = currentMonth.atEndOfMonth();
                    break;
                case "quarter":
                    // 当前季度
                    int currentQuarter = (LocalDate.now().getMonthValue() - 1) / 3 + 1;
                    int startMonth = (currentQuarter - 1) * 3 + 1;
                    startDate = LocalDate.of(LocalDate.now().getYear(), startMonth, 1);
                    endDate = LocalDate.of(LocalDate.now().getYear(), startMonth + 2, 1).plusMonths(1).minusDays(1);
                    break;
                case "year":
                    // 当前年度
                    startDate = LocalDate.of(LocalDate.now().getYear(), 1, 1);
                    endDate = LocalDate.of(LocalDate.now().getYear(), 12, 31);
                    break;
                case "custom":
                    // 自定义日期范围
                    if (query.getDateRange() == null || query.getDateRange().size() != 2) {
                        throw new BusinessException("自定义日期范围必须提供两个日期");
                    }
                    startDate = query.getDateRange().get(0);
                    endDate = query.getDateRange().get(1);
                    break;
                default:
                    // 默认为当�?
                    startDate = LocalDate.now().withDayOfMonth(1);
                    endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("productType", query.getProductType());
            
            // 计算上一期的日期范围，根据当前周期类型计�?
            LocalDate lastPeriodStart;
            LocalDate lastPeriodEnd;
            
            switch (query.getPeriod()) {
                case "month":
                    lastPeriodStart = startDate.minusMonths(1);
                    lastPeriodEnd = endDate.minusMonths(1);
                    break;
                case "quarter":
                    lastPeriodStart = startDate.minusMonths(3);
                    lastPeriodEnd = endDate.minusMonths(3);
                    break;
                case "year":
                    lastPeriodStart = startDate.minusYears(1);
                    lastPeriodEnd = endDate.minusYears(1);
                    break;
                default:
                    // 自定义周期，取上一个同等长度的时间�?
                    long days = endDate.toEpochDay() - startDate.toEpochDay() + 1;
                    lastPeriodStart = startDate.minusDays(days);
                    lastPeriodEnd = endDate.minusDays(days);
            }
            
            params.put("lastPeriodStart", lastPeriodStart);
            params.put("lastPeriodEnd", lastPeriodEnd);
            
            // 查询贷款统计数据
            Map<String, Object> statsData = statisticsMapper.getLoanStatsOverview(params);
            
            // 构造返回对�?
            LoanStatsDTO stats = new LoanStatsDTO();
            stats.setTotalAmount(getBigDecimal(statsData, "totalAmount"));
            stats.setTotalCount(getInteger(statsData, "totalCount"));
            stats.setAvgAmount(getBigDecimal(statsData, "avgAmount"));
            stats.setAmountCompare(getBigDecimal(statsData, "amountCompare"));
            stats.setCountCompare(getBigDecimal(statsData, "countCompare"));
            stats.setAvgAmountCompare(getBigDecimal(statsData, "avgAmountCompare"));
            
            return stats;
        } catch (Exception e) {
            log.error("获取贷款统计概览数据失败", e);
            throw new BusinessException("获取贷款统计概览数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取贷款图表数据
     */
    @Override
    public LoanChartDTO getLoanCharts(LoanQueryDTO query) {
        try {
            // 处理查询参数
            LocalDate startDate;
            LocalDate endDate;
            
            // 处理统计周期
            switch (query.getPeriod()) {
                case "month":
                    // �?个月
                    startDate = LocalDate.now().minusMonths(5).withDayOfMonth(1);
                    endDate = LocalDate.now();
                    break;
                case "quarter":
                    // �?个季�?
                    int currentMonth = LocalDate.now().getMonthValue();
                    int currentQuarter = (currentMonth - 1) / 3 + 1;
                    int quarterStartMonth = (currentQuarter - 1) * 3 + 1;
                    startDate = LocalDate.of(LocalDate.now().getYear() - 1, quarterStartMonth, 1);
                    endDate = LocalDate.now();
                    break;
                case "year":
                    // �?�?
                    startDate = LocalDate.of(LocalDate.now().getYear() - 2, 1, 1);
                    endDate = LocalDate.now();
                    break;
                case "custom":
                    // 自定义日期范围
                    if (query.getDateRange() == null || query.getDateRange().size() != 2) {
                        throw new BusinessException("自定义日期范围必须提供两个日期");
                    }
                    startDate = query.getDateRange().get(0);
                    endDate = query.getDateRange().get(1);
                    break;
                default:
                    // 默认为近6个月
                    startDate = LocalDate.now().minusMonths(5).withDayOfMonth(1);
                    endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("period", query.getPeriod());
            params.put("productType", query.getProductType());
            
            // 查询图表数据
            List<Map<String, Object>> chartDataList = statisticsMapper.getLoanChartData(params);
            
            // 构建返回的图表数据对�?
            LoanChartDTO chart = processLoanChartData(chartDataList, query.getPeriod());
            
            return chart;
        } catch (Exception e) {
            log.error("获取贷款图表数据失败", e);
            throw new BusinessException("获取贷款图表数据失败: " + e.getMessage());
        }
    }

    /**
     * 处理贷款图表数据
     */
    private LoanChartDTO processLoanChartData(List<Map<String, Object>> dataList, String period) {
        LoanChartDTO chart = new LoanChartDTO();
        
        // 处理图表数据...
        // 这里根据dataList构建LoanChartDTO对象
        
        return chart;
    }

    /**
     * 获取贷款明细列表
     */
    @Override
    public Page<Map<String, Object>> getLoanList(LoanQueryDTO query) {
        try {
            // 处理默认�?
            if (query.getCurrentPage() == null || query.getCurrentPage() < 1) {
                query.setCurrentPage(1);
            }
            if (query.getPageSize() == null || query.getPageSize() < 1) {
                query.setPageSize(10);
            }
            
            // 处理查询参数
            LocalDate startDate;
            LocalDate endDate;
            
            // 处理统计周期
            switch (query.getPeriod()) {
                case "month":
                    // 当月
                    startDate = LocalDate.now().withDayOfMonth(1);
                    endDate = LocalDate.now();
                    break;
                case "quarter":
                    // 当前季度
                    int currentQuarter = (LocalDate.now().getMonthValue() - 1) / 3 + 1;
                    int startMonth = (currentQuarter - 1) * 3 + 1;
                    startDate = LocalDate.of(LocalDate.now().getYear(), startMonth, 1);
                    endDate = LocalDate.now();
                    break;
                case "year":
                    // 当前年度
                    startDate = LocalDate.of(LocalDate.now().getYear(), 1, 1);
                    endDate = LocalDate.now();
                    break;
                case "custom":
                    // 自定义日期范围
                    if (query.getDateRange() == null || query.getDateRange().size() != 2) {
                        throw new BusinessException("自定义日期范围必须提供两个日期");
                    }
                    startDate = query.getDateRange().get(0);
                    endDate = query.getDateRange().get(1);
                    break;
                default:
                    // 默认为当�?
                    startDate = LocalDate.now().withDayOfMonth(1);
                    endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("productType", query.getProductType());
            params.put("loanStatus", query.getLoanStatus());
            params.put("orderBy", query.getOrderBy());
            params.put("orderType", query.getOrderType());
            
            // 构造分页对�?
            Page<Map<String, Object>> page = new Page<>(query.getCurrentPage(), query.getPageSize());
            
            // 查询总数
            Integer total = statisticsMapper.countLoanList(params);
            page.setTotal(total);
            
            // 查询明细列表
            List<Map<String, Object>> list = statisticsMapper.getLoanList(params, (query.getCurrentPage() - 1) * query.getPageSize(), query.getPageSize());
            page.setRecords(list);
            
            return page;
        } catch (Exception e) {
            log.error("获取贷款明细列表失败", e);
            throw new BusinessException("获取贷款明细列表失败: " + e.getMessage());
        }
    }

    /**
     * 导出贷款报表数据
     */
    @Override
    public byte[] exportLoanReport(LoanQueryDTO query) {
        try {
            // 创建Excel工作�?
            Workbook workbook = new XSSFWorkbook();
            
            // 导出类型：summary(汇�?、detail(明细)
            if ("summary".equals(query.getExportType())) {
                // 导出汇总数�?
                LoanStatsDTO stats = getLoanStats(query);
                LoanChartDTO chart = getLoanCharts(query);
                createLoanSummarySheet(workbook, stats, chart, query);
            } else {
                // 导出明细数据 - 最多导出10000条
                Map<String, Object> params = new HashMap<>();
                // 设置查询参数
                if (query.getDateRange() != null && query.getDateRange().size() == 2) {
                    params.put("startDate", query.getDateRange().get(0));
                    params.put("endDate", query.getDateRange().get(1));
                }
                params.put("productType", query.getProductType());
                
                List<Map<String, Object>> list = statisticsMapper.getLoanList(params, 0, 10000);
                createLoanDetailSheet(workbook, list, query);
            }
            
            // 生成Excel文件字节�?
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("导出贷款报表数据失败", e);
            throw new BusinessException("导出贷款报表数据失败: " + e.getMessage());
        }
    }

    /**
     * 创建贷款汇总数据工作表
     */
    private void createLoanSummarySheet(Workbook workbook, LoanStatsDTO stats, LoanChartDTO chart, LoanQueryDTO query) {
        // 此方法实现省略，用于创建Excel工作表并填充贷款汇总数�?
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 创建贷款明细数据工作�?
     */
    private void createLoanDetailSheet(Workbook workbook, List<Map<String, Object>> list, LoanQueryDTO query) {
        // 此方法实现省略，用于创建Excel工作表并填充贷款明细数据
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 安全获取BigDecimal值，避免空指针异�?
     */
    private BigDecimal getBigDecimal(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        try {
            return new BigDecimal(value.toString());
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }
    
    /**
     * 安全获取Integer值，避免空指针异�?
     */
    private Integer getInteger(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return 0;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取风险统计概览数据
     */
    @Override
    public RiskStatsDTO getRiskStats(List<LocalDate> dateRange, String riskLevel) {
        try {
            // 处理日期范围
            LocalDate startDate;
            LocalDate endDate;
            
            if (dateRange != null && dateRange.size() == 2) {
                startDate = dateRange.get(0);
                endDate = dateRange.get(1);
            } else {
                // 默认为当�?
                startDate = LocalDate.now().withDayOfMonth(1);
                endDate = LocalDate.now();
            }
            
            // 处理风险等级
            if (riskLevel == null || riskLevel.trim().isEmpty()) {
                riskLevel = "all"; // 默认查询所有风险等�?
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("riskLevel", riskLevel);
            
            // 计算上月同期的日期范围，用于环比计算
            LocalDate lastPeriodStart = startDate.minusMonths(1);
            LocalDate lastPeriodEnd = endDate.minusMonths(1);
            params.put("lastPeriodStart", lastPeriodStart);
            params.put("lastPeriodEnd", lastPeriodEnd);
            
            // 查询风险统计数据
            Map<String, Object> statsData = statisticsMapper.getRiskStatsOverview(params);
            
            // 构造返回对�?
            RiskStatsDTO stats = new RiskStatsDTO();
            stats.setWarningCount(getInteger(statsData, "warningCount"));
            stats.setWarningRate(getBigDecimal(statsData, "warningRate"));
            stats.setHighRiskCount(getInteger(statsData, "highRiskCount"));
            stats.setHighRiskRate(getBigDecimal(statsData, "highRiskRate"));
            stats.setBlacklistCount(getInteger(statsData, "blacklistCount"));
            stats.setBlacklistRate(getBigDecimal(statsData, "blacklistRate"));
            stats.setProcessRate(getBigDecimal(statsData, "processRate"));
            stats.setProcessRateChange(getBigDecimal(statsData, "processRateChange"));
            
            return stats;
        } catch (Exception e) {
            log.error("获取风险统计概览数据失败", e);
            throw new BusinessException("获取风险统计概览数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取风险图表数据
     */
    @Override
    public Map<String, Object> getRiskCharts(List<LocalDate> dateRange, String riskLevel) {
        try {
            // 处理日期范围
            LocalDate startDate;
            LocalDate endDate;
            
            if (dateRange != null && dateRange.size() == 2) {
                startDate = dateRange.get(0);
                endDate = dateRange.get(1);
            } else {
                // 默认为近6个月
                startDate = LocalDate.now().minusMonths(5).withDayOfMonth(1);
                endDate = LocalDate.now();
            }
            
            // 处理风险等级
            if (riskLevel == null || riskLevel.trim().isEmpty()) {
                riskLevel = "all"; // 默认查询所有风险等�?
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("riskLevel", riskLevel);
            
            // 查询风险图表数据
            List<Map<String, Object>> chartDataList = statisticsMapper.getRiskChartData(params);
            
            // 处理并返回图表数�?
            return processRiskChartData(chartDataList);
        } catch (Exception e) {
            log.error("获取风险图表数据失败", e);
            throw new BusinessException("获取风险图表数据失败: " + e.getMessage());
        }
    }

    /**
     * 处理风险图表数据
     */
    private Map<String, Object> processRiskChartData(List<Map<String, Object>> dataList) {
        Map<String, Object> result = new HashMap<>();
        
        // 处理图表数据...
        // 这里根据dataList构建结果Map
        
        return result;
    }

    /**
     * 获取风险明细列表
     */
    @Override
    public Page<Map<String, Object>> getRiskList(LocalDate startDate, LocalDate endDate, 
                                               String riskLevel, String customerName,
                                               Integer currentPage, Integer pageSize) {
        try {
            // 处理默认�?
            if (currentPage == null || currentPage < 1) {
                currentPage = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 10;
            }
            if (startDate == null) {
                // 默认为当月初
                startDate = LocalDate.now().withDayOfMonth(1);
            }
            if (endDate == null) {
                // 默认为当前日�?
                endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("riskLevel", riskLevel);
            params.put("customerName", customerName);
            
            // 构造分页对�?
            Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
            
            // 查询总数
            Integer total = statisticsMapper.countRiskList(params);
            page.setTotal(total);
            
            // 查询明细列表
            List<Map<String, Object>> list = statisticsMapper.getRiskList(params, (currentPage - 1) * pageSize, pageSize);
            page.setRecords(list);
            
            return page;
        } catch (Exception e) {
            log.error("获取风险明细列表失败", e);
            throw new BusinessException("获取风险明细列表失败: " + e.getMessage());
        }
    }

    /**
     * 导出风险报表数据
     */
    @Override
    public byte[] exportRiskReport(LocalDate startDate, LocalDate endDate,
                                 String riskLevel, String exportType) {
        try {
            // 创建Excel工作�?
            Workbook workbook = new XSSFWorkbook();
            
            // 导出类型：summary(汇�?、detail(明细)
            if ("summary".equals(exportType)) {
                // 导出汇总数�?
                List<LocalDate> dateRange = Arrays.asList(startDate, endDate);
                RiskStatsDTO stats = getRiskStats(dateRange, riskLevel);
                Map<String, Object> charts = getRiskCharts(dateRange, riskLevel);
                createRiskSummarySheet(workbook, stats, charts, startDate, endDate, riskLevel);
            } else {
                // 导出明细数据 - 最多导出10000条
                Map<String, Object> params = new HashMap<>();
                params.put("startDate", startDate);
                params.put("endDate", endDate);
                params.put("riskLevel", riskLevel);
                
                List<Map<String, Object>> list = statisticsMapper.getRiskList(params, 0, 10000);
                createRiskDetailSheet(workbook, list, startDate, endDate, riskLevel);
            }
            
            // 生成Excel文件字节�?
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("导出风险报表数据失败", e);
            throw new BusinessException("导出风险报表数据失败: " + e.getMessage());
        }
    }

    /**
     * 创建风险汇总数据工作表
     */
    private void createRiskSummarySheet(Workbook workbook, RiskStatsDTO stats, Map<String, Object> charts,
                                     LocalDate startDate, LocalDate endDate, String riskLevel) {
        // 此方法实现省略，用于创建Excel工作表并填充风险汇总数�?
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 创建风险明细数据工作�?
     */
    private void createRiskDetailSheet(Workbook workbook, List<Map<String, Object>> list,
                                    LocalDate startDate, LocalDate endDate, String riskLevel) {
        // 此方法实现省略，用于创建Excel工作表并填充风险明细数据
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 获取逾期统计数据
     */
    @Override
    public OverdueStatsDTO getOverdueStats(List<LocalDate> dateRange) {
        try {
            // 处理日期范围
            LocalDate startDate;
            LocalDate endDate;
            
            if (dateRange != null && dateRange.size() == 2) {
                startDate = dateRange.get(0);
                endDate = dateRange.get(1);
            } else {
                // 默认为当�?
                startDate = LocalDate.now().withDayOfMonth(1);
                endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            // 计算上月同期的日期范�?
            LocalDate lastPeriodStart = startDate.minusMonths(1);
            LocalDate lastPeriodEnd = endDate.minusMonths(1);
            params.put("lastPeriodStart", lastPeriodStart);
            params.put("lastPeriodEnd", lastPeriodEnd);
            
            // 查询逾期统计数据
            Map<String, Object> statsData = statisticsMapper.getOverdueStatsOverview(params);
            
            // 构造返回对�?
            OverdueStatsDTO stats = new OverdueStatsDTO();
            stats.setOverdueCount(getInteger(statsData, "overdueCount"));
            stats.setOverdueAmount(getBigDecimal(statsData, "overdueAmount"));
            stats.setOverdueRate(getBigDecimal(statsData, "overdueRate"));
            stats.setOverdueRateChange(getBigDecimal(statsData, "overdueRateChange"));
            stats.setAvgOverdueDays(getBigDecimal(statsData, "avgOverdueDays"));
            
            // 设置逾期天数分布
            @SuppressWarnings("unchecked")
            Map<String, Integer> daysDistribution = (Map<String, Integer>) statsData.get("daysDistribution");
            if (daysDistribution != null) {
                stats.setDaysDistribution(daysDistribution);
            }
            
            // 设置逾期月度趋势
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> monthlyTrendData = (List<Map<String, Object>>) statsData.get("monthlyTrend");
            if (monthlyTrendData != null) {
                List<OverdueStatsDTO.MonthlyTrend> monthlyTrends = new ArrayList<>();
                for (Map<String, Object> item : monthlyTrendData) {
                    OverdueStatsDTO.MonthlyTrend trend = new OverdueStatsDTO.MonthlyTrend();
                    trend.setMonth((String) item.get("month"));
                    trend.setCount(getInteger(item, "count"));
                    trend.setAmount(getBigDecimal(item, "amount"));
                    trend.setRate(getBigDecimal(item, "rate"));
                    monthlyTrends.add(trend);
                }
                stats.setMonthlyTrend(monthlyTrends);
            }
            
            return stats;
        } catch (Exception e) {
            log.error("获取逾期统计数据失败", e);
            throw new BusinessException("获取逾期统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取放款统计概览数据
     */
    @Override
    public LendingStatsDTO getLendingStats(LocalDate startDate, LocalDate endDate) {
        try {
            // 处理默认�?
            if (startDate == null) {
                startDate = LocalDate.now().withDayOfMonth(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 计算上个月的日期范围，用于环比计�?
            LocalDate lastPeriodStart = startDate.minusMonths(1);
            LocalDate lastPeriodEnd = endDate.minusMonths(1);
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("lastPeriodStart", lastPeriodStart);
            params.put("lastPeriodEnd", lastPeriodEnd);
            
            // 查询放款统计数据
            Map<String, Object> statsData = statisticsMapper.getLendingStatsOverview(params);
            
            // 构造返回对�?
            LendingStatsDTO stats = new LendingStatsDTO();
            stats.setTotalAmount(getBigDecimal(statsData, "totalAmount"));
            stats.setTotalCount(getInteger(statsData, "totalCount"));
            stats.setAvgAmount(getBigDecimal(statsData, "avgAmount"));
            stats.setSuccessRate(getBigDecimal(statsData, "successRate"));
            stats.setAmountCompare(getBigDecimal(statsData, "amountCompare"));
            stats.setCountCompare(getBigDecimal(statsData, "countCompare"));
            stats.setAvgProcessTime(getBigDecimal(statsData, "avgProcessTime"));
            stats.setProcessTimeCompare(getBigDecimal(statsData, "processTimeCompare"));
            
            return stats;
        } catch (Exception e) {
            log.error("获取放款统计概览数据失败", e);
            throw new BusinessException("获取放款统计概览数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取放款图表数据
     */
    @Override
    public Map<String, Object> getLendingCharts(LocalDate startDate, LocalDate endDate, String period) {
        try {
            // 处理默认�?
            if (startDate == null) {
                // 默认为近6个月
                startDate = LocalDate.now().minusMonths(5).withDayOfMonth(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            if (period == null || period.trim().isEmpty()) {
                period = "month"; // 默认按月统计
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("period", period);
            
            // 查询放款图表数据
            List<Map<String, Object>> chartDataList = statisticsMapper.getLendingChartData(params);
            
            // 处理并返回图表数�?
            return processLendingChartData(chartDataList, period);
        } catch (Exception e) {
            log.error("获取放款图表数据失败", e);
            throw new BusinessException("获取放款图表数据失败: " + e.getMessage());
        }
    }

    /**
     * 处理放款图表数据
     */
    private Map<String, Object> processLendingChartData(List<Map<String, Object>> dataList, String period) {
        Map<String, Object> result = new HashMap<>();
        
        // 处理图表数据...
        // 这里根据dataList构建结果Map
        
        return result;
    }

    /**
     * 获取放款明细列表
     */
    @Override
    public Page<Map<String, Object>> getLendingList(LocalDate startDate, LocalDate endDate,
                                                 String productType, String customerName,
                                                 Integer currentPage, Integer pageSize) {
        try {
            // 处理默认�?
            if (currentPage == null || currentPage < 1) {
                currentPage = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 10;
            }
            if (startDate == null) {
                startDate = LocalDate.now().withDayOfMonth(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            params.put("productType", productType);
            params.put("customerName", customerName);
            
            // 构造分页对�?
            Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
            
            // 查询总数
            Integer total = statisticsMapper.countLendingList(params);
            page.setTotal(total);
            
            // 查询明细列表
            List<Map<String, Object>> list = statisticsMapper.getLendingList(params, (currentPage - 1) * pageSize, pageSize);
            page.setRecords(list);
            
            return page;
        } catch (Exception e) {
            log.error("获取放款明细列表失败", e);
            throw new BusinessException("获取放款明细列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取放款失败分析
     */
    @Override
    public Map<String, Object> getLendingFailureAnalysis(LocalDate startDate, LocalDate endDate) {
        try {
            // 处理默认�?
            if (startDate == null) {
                startDate = LocalDate.now().withDayOfMonth(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            // 查询放款失败分析数据
            Map<String, Object> analysisData = statisticsMapper.getLendingFailureAnalysis(params);
            
            // 返回分析数据
            return analysisData;
        } catch (Exception e) {
            log.error("获取放款失败分析失败", e);
            throw new BusinessException("获取放款失败分析失败: " + e.getMessage());
        }
    }

    /**
     * 导出放款报表数据
     */
    @Override
    public byte[] exportLendingReport(LocalDate startDate, LocalDate endDate,
                                    String productType, String exportType) {
        try {
            // 创建Excel工作�?
            Workbook workbook = new XSSFWorkbook();
            
            // 导出类型：summary(汇�?、detail(明细)
            if ("summary".equals(exportType)) {
                // 导出汇总数�?
                LendingStatsDTO stats = getLendingStats(startDate, endDate);
                Map<String, Object> charts = getLendingCharts(startDate, endDate, "month");
                createLendingSummarySheet(workbook, stats, charts, startDate, endDate);
            } else {
                // 导出明细数据 - 最多导出10000条
                Map<String, Object> params = new HashMap<>();
                params.put("startDate", startDate);
                params.put("endDate", endDate);
                params.put("productType", productType);
                
                List<Map<String, Object>> list = statisticsMapper.getLendingList(params, 0, 10000);
                createLendingDetailSheet(workbook, list, startDate, endDate, productType);
            }
            
            // 生成Excel文件字节�?
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("导出放款报表数据失败", e);
            throw new BusinessException("导出放款报表数据失败: " + e.getMessage());
        }
    }

    /**
     * 创建放款汇总数据工作表
     */
    private void createLendingSummarySheet(Workbook workbook, LendingStatsDTO stats, Map<String, Object> charts,
                                        LocalDate startDate, LocalDate endDate) {
        // 此方法实现省略，用于创建Excel工作表并填充放款汇总数�?
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 创建放款明细数据工作�?
     */
    private void createLendingDetailSheet(Workbook workbook, List<Map<String, Object>> list,
                                       LocalDate startDate, LocalDate endDate, String productType) {
        // 此方法实现省略，用于创建Excel工作表并填充放款明细数据
        // 实际项目中根据需求实现Excel内容填充
    }

    /**
     * 获取放款效率分析
     */
    @Override
    public Map<String, Object> getLendingEfficiency(LocalDate startDate, LocalDate endDate) {
        try {
            // 处理默认�?
            if (startDate == null) {
                startDate = LocalDate.now().withDayOfMonth(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 构造查询参�?
            Map<String, Object> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            // 查询放款效率分析数据
            Map<String, Object> efficiencyData = statisticsMapper.getLendingEfficiency(params);
            
            // 返回分析数据
            return efficiencyData;
        } catch (Exception e) {
            log.error("获取放款效率分析失败", e);
            throw new BusinessException("获取放款效率分析失败: " + e.getMessage());
        }
    }
} 
